import fs from "fs";
import path from "path";
import https from "https";
// 文件后缀名
export const ext = [".png", ".jpg", ".jpeg"];
// 最大体积
export const maxSize = 5200000; // 5MB == 5242848.754299136

// 检查输出文件夹
export function checkOutput(output) {
  return new Promise((resolve, reject) => {
    if (!output) resolve(null);
    output = path.resolve(process.cwd(), output || "");
    fs.stat(output, (err, data) => {
      if (err) {
        reject("请指定一个有效的输出文件夹1");
      } else if (data.isDirectory()) {
        resolve(output);
      } else {
        reject("请指定一个有效的输出文件夹2");
      }
    });
  });
}
// 获取处理文件列表
export function getImageList(option, log) {
  const list = [];
  const { input: pathname, deep: deepLoop, ext, maxSize } = option;
  try {
    loop(pathname, true);
    function loop(pathname, deep) {
      const stat = fs.statSync(pathname);
      if (deep && stat.isDirectory()) {
        fs.readdirSync(pathname).forEach((filePathname) => {
          loop(path.join(pathname, filePathname), deepLoop);
        });
      } else if (
        stat.isFile() &&
        stat.size <= maxSize &&
        ext.includes(path.extname(pathname))
      ) {
        list.push(pathname);
      }
    }
  } catch (error) {
    log.error("警告：请指定一个有效的目标文件/文件夹");
  }
  return list;
}
// 获取文件上传请求参数
export function getXHROptions() {
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  const option = {
    method: "POST",
    hostname: "tinypng.com",
    path: "/web/shrink",
    headers: {
      rejectUnauthorized: false,
      "X-Forwarded-For": Array(4)
        .fill(1)
        .map(() => Math.ceil(Math.random() * 255))
        .join("."),
      "Cache-Control": "no-cache",
      "Content-Type": "application/x-www-form-urlencoded",
      "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36",
    },
  };
  return option;
}
// 文件上传
export function fileUpload(imgPath, log) {
  return new Promise((resolve, reject) => {
    const config = getXHROptions();
    const fileData = fs.readFileSync(imgPath)
    config.headers['Content-Length'] = Buffer.byteLength(fileData)
    let req = https.request(config, (res) => {
      res.on("data", (buf) => {
        let serverData = JSON.parse(buf.toString());
        if (serverData.error) {
          log.error(serverData.error);
          reject("警告：压缩失败, 当前文件 " + imgPath);
        } else {
          resolve(serverData);
        }
      });
    });
    req.write(fileData, "binary");
    req.on("error", (e) => {
      log.error(e);
      reject("警告：上传失败, 当前文件 " + imgPath);
      req.destroy();
    });
    req.end();
  });
}
// 下载图片
export function downloadImage(webImgUrl, log) {
  return new Promise((resolve, reject) => {
    if (webImgUrl.slice(0, 8) !== 'https://') {
      webImgUrl = 'https://' + webImgUrl.slice(7, webImgUrl.length)
    }
    try {
      https
        .get(webImgUrl, (res) => {
          let body = "";
          res.setEncoding("binary");
          res.on("data", (chunk) => (body += chunk));
          res.on("end", () => resolve(body));
        })
        .on("error", (error) => {
          log.error(error);
          reject("警告：下载失败, 当前文件 " + webImgUrl);
        });
    } catch (error) {
      log.error(error);
      reject("警告：下载失败, 当前文件 " + webImgUrl);
    }
  });
}
